package net.studou.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.studou.bean.tools.BeanUtils;
import net.studou.bean.tools.Properties;
import net.studou.dao.IoLogDao;
import net.studou.exception.RechargeNoExistException;
import net.studou.exception.UserNotExistException;
import net.studou.po.IoLog;
import net.studou.po.Page;
import net.studou.po.User;
import net.studou.tools.Utils;
import net.studou.vo.VIoLog;

import org.springframework.stereotype.Component;

@Component("ioLogService")
public class IoLogService {
	@Resource(name = "ioLogDao")
	private IoLogDao ioLogDao;

	@Resource(name = "userService")
	private UserService userService;

	/**
	 * 充值
	 * 
	 * @param ioLog
	 * @param user
	 * @return
	 * @throws UserNotExistException 
	 * @throws RechargeNoExistException 
	 */
	@SuppressWarnings("unchecked")
	public void recharge(IoLog ioLog, User user) throws UserNotExistException, RechargeNoExistException {
		User dbUser = userService.isNotExist(user.getUserName());
		if (dbUser == null) {
			throw new UserNotExistException("User not exist");
		}
		List<IoLog> logs = ioLogDao.findByProperty("ioNo", ioLog.getIoNo());
		if (logs == null || logs.size() > 0) {
			throw new RechargeNoExistException("Recharge no is exist");
		}

		ioLog.setUser(dbUser);
		ioLog.setIoType(IoLog.TYPE_RECHARGE);
		ioLog.setCreateTime(Utils.getChinaDateTime());
		ioLog.setStatus(IoLog.STATUS_WAIT);
		ioLogDao.save(ioLog);
	}

	/**
	 * 查询交易记录
	 * 
	 * @param ioLog
	 * @param user
	 * @param page
	 * @return
	 */
	public List<VIoLog> findIO(IoLog ioLog, User user, Page page) {
		List<IoLog> list = ioLogDao.findIO(ioLog, user, page);
		List<VIoLog> vlist = new ArrayList<VIoLog>();
		if (list != null && list.size() > 0) {
			String source = "ioNo, ioType, money, ago, after, createTime, status, details, tbUrl, qq, realName";
			String target = "ioNo, ioType, money, ago, after, createTime, status, details, tbUrl, qq, realName";
			Properties properties = new Properties(source, target);
			BeanUtils.copyList(list, vlist, properties);
		}
		return vlist;
	}

}
